const Router = require('@koa/router')
const router = new Router()

const { shop } = require('../vri')
const db = require('../db')

// 我的店铺
router.get('/my', async (ctx) => {
  // 登陆验证
  const { user } = ctx.state
  if (!user) return ctx.error('401')

  const data = await db.first({
    form: 'shop',
    where: {
      userid: user.id,
    },
  })
  if (!data) return ctx.error(431)
  ctx.body = {
    code: 200,
    data,
  }
})
// 创建店铺
router.post('/add', async (ctx) => {
  // 登陆验证
  const { user } = ctx.state
  if (!user) return ctx.error('401')
  const { body } = ctx.request
  const { adopt, error, value } = shop.add.verifies(body)
  if (!adopt) return ctx.error(430, { error: error.toString() })
  const ys = await db.count({
    form: 'shop',
    where: {
      userid: user.id,
    },
  })
  if (ys)
    return (ctx.body = {
      code: 401,
      msg: '已拥有店铺',
    })
  const { lastId: id } = await db.insert({
    form: 'shop',
    value: {
      ...value,
      userid: user.id,
    },
    lastId: true,
  })
  ctx.body = {
    code: 200,
    msg: '添加成功',
    id,
  }
})

// 修改店铺
router.post('/modify', async (ctx) => {
  // 登陆验证
  const { user } = ctx.state
  if (!user) return ctx.error('401')
  const { body } = ctx.request
  const { adopt, error, value } = shop.modify.verifies(body)
  if (!adopt) return ctx.error(430, { error: error.toString() })
  const { affectedRows } = await db.update({
    form: 'shop',
    where: {
      userid: user.id,
    },
    set: value,
  })
  if (!affectedRows) return ctx.error(431)
  ctx.body = {
    code: 200,
    msg: '成功',
  }
})

module.exports = router.routes()
